package com.github.monkeywie.proxyee.intercept;

import com.github.monkeywie.proxyee.handler.HttpProxyServerHandle;
import com.github.monkeywie.proxyee.intercept.common.CertDownIntercept;
import com.github.monkeywie.proxyee.intercept.common.FullResponseIntercept;
import com.github.monkeywie.proxyee.intercept.common.LogIntercept;
import com.github.monkeywie.proxyee.log.LogRecorder;
import com.github.monkeywie.proxyee.log.LogRecorderFactory;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpProxyInterceptInitializer {
    private final static LogRecorder logRecorder = LogRecorderFactory.getRecorder(HttpProxyInterceptInitializer.class);

    public void init(HttpProxyInterceptPipeline pipeline) {
        pipeline.addLast(new CertDownIntercept());
        pipeline.addLast(new FullResponseIntercept() {

            @Override
            public boolean match(HttpRequest httpRequest, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) {
                return false;
            }

            @Override
            public void handelResponse(HttpRequest httpRequest, FullHttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) {
                //打印原始响应信息
                //System.out.println(">>>>>>>>>>>>>>>RESPONSE>>>>>>>>>>>>");
                logRecorder.info(httpRequest.method()+" http://"+httpRequest.headers().get("host")+httpRequest.uri());
//                System.out.println(httpResponse.toString());
                String type=httpResponse.headers().get("Content-Type");
                if(type!=null&& (type.toLowerCase().contains("text") ||type.toLowerCase().contains("json")))
                {
                    logRecorder.info(httpResponse.content().toString(Charset.defaultCharset()));
                }

                //修改响应头和响应体
//                httpResponse.headers().set("handel", "edit head");
                    /*int index = ByteUtil.findText(httpResponse.content(), "<head>");
                    ByteUtil.insertText(httpResponse.content(), index, "<script>alert(1)</script>");*/
//                httpResponse.content().writeBytes("<script>alert('hello proxyee')</script>".getBytes());

            }
        });
    }

}
